import { useState, useEffect, useCallback } from 'react';

export function useUnifiedDevices(specialty?: string) {
  const [devices, setDevices] = useState<any[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const fetchDevices = useCallback(async () => {
    try {
      setLoading(true);
      setError(null);
      
      const url = specialty 
        ? `/api/sqlite-devices?specialty=${encodeURIComponent(specialty)}`
        : '/api/sqlite-devices';
      
      const response = await fetch(url, { cache: 'no-store' });
      if (!response.ok) {
        throw new Error('获取设备数据失败');
      }
      
      const data = await response.json();
      // SQLite API返回的是设备数组，不是包装在success字段中
      const devices = Array.isArray(data) ? data : [];
      
      // 转换SQLite数据格式到Hook期望的格式
      const convertedDevices = devices.map((device: any) => ({
        id: device.id,
        displayId: device.device_id,
        name: device.name,
        classificationCode: device.classification_code,
        classificationName: device.classification_name,
        序号: device.sequence_number?.toString() || '',
        specialty: device.specialty,
        namingTableId: device.naming_table_id,
        positionTableId: device.position_table_id,
        baseParamsTableId: device.base_params_table_id,
        techSpecTableId: device.tech_spec_table_id,
        备注: device.remarks || ''
      }));
      
      // 按device_id的逻辑顺序排序，让同类设备聚集在一起
      const sortedDevices = convertedDevices.sort((a, b) => {
        const aId = a.displayId || '';
        const bId = b.displayId || '';
        
        // 提取基础ID和序号 - 更精确的解析
        const parseDeviceId = (deviceId: string) => {
          // 处理形如 "配管-0001" 或 "配管-0001-1" 的格式
          const match = deviceId.match(/^(.+?-\d+)(?:-(\d+))?$/);
          if (match) {
            const baseId = match[1]; // 例如："配管-0001"
            const suffix = match[2] ? parseInt(match[2], 10) : 0; // 例如：1 或 0（没有后缀）
            return { baseId, suffix, fullId: deviceId };
          }
          
          // 如果不匹配标准格式，按原样处理
          return { baseId: deviceId, suffix: 0, fullId: deviceId };
        };
        
        const aInfo = parseDeviceId(aId);
        const bInfo = parseDeviceId(bId);
        
        // 首先按基础ID排序
        const baseIdComparison = aInfo.baseId.localeCompare(bInfo.baseId, 'zh-CN', { numeric: true });
        if (baseIdComparison !== 0) {
          return baseIdComparison;
        }
        
        // 如果基础ID相同，按序号排序（父设备suffix=0排在前面）
        return aInfo.suffix - bInfo.suffix;
      });
      
      setDevices(sortedDevices);
    } catch (err) {
      setError(err instanceof Error ? err.message : '未知错误');
    } finally {
      setLoading(false);
    }
  }, [specialty]);

  useEffect(() => {
    fetchDevices();
  }, [fetchDevices]);

  const addDevice = async (deviceData: Partial<any>): Promise<any | null> => {
    try {
      setError(null);
      // 移除id字段，避免主键冲突
      const { id, ...rest } = deviceData;
      // 转换数据格式到SQLite期望的格式
      const sqliteDeviceData = {
        name: rest.name || '',
        classification_name: rest.classificationName || '',
        classification_code: rest.classificationCode || '',
        specialty: rest.specialty || '',
        naming_table_id: rest.namingTableId || '',
        position_table_id: rest.positionTableId || '',
        base_params_table_id: rest.baseParamsTableId || '',
        tech_spec_table_id: rest.techSpecTableId || '',
        sequence_number: rest.sequence_number || rest.序号 || '',
        remarks: rest.备注 || '',
        // 传递原始设备ID用于生成递增序号
        original_device_id: rest.original_device_id
      };
      
      console.log('传递给API的设备数据:', sqliteDeviceData);
      
      const addResponse = await fetch('/api/sqlite-devices', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify(sqliteDeviceData),
      });
      if (!addResponse.ok) {
        throw new Error('添加设备失败');
      }
      const data = await addResponse.json();
      // 添加成功后刷新设备列表
      await fetchDevices();
      return data.device || null;
    } catch (err) {
      setError(err instanceof Error ? err.message : '未知错误');
      return null;
    }
  };

  const updateDevice = async (deviceId: number, updates: Partial<any>): Promise<any | null> => {
    try {
      setError(null);
      
      // 转换数据格式到SQLite期望的格式
      const sqliteUpdates: any = {};
      
      if (updates.name) {
        sqliteUpdates.name = updates.name;
      }
      if (updates.classificationName) {
        sqliteUpdates.classification_name = updates.classificationName;
      }
      if (updates.classificationCode) {
        sqliteUpdates.classification_code = updates.classificationCode;
      }
      if (updates.specialty) {
        sqliteUpdates.specialty = updates.specialty;
      }
      if (updates.namingTableId) {
        sqliteUpdates.naming_table_id = updates.namingTableId;
      }
      if (updates.positionTableId) {
        sqliteUpdates.position_table_id = updates.positionTableId;
      }
      if (updates.baseParamsTableId) {
        sqliteUpdates.base_params_table_id = updates.baseParamsTableId;
      }
      if (updates.techSpecTableId) {
        sqliteUpdates.tech_spec_table_id = updates.techSpecTableId;
      }
      if (updates.序号) {
        sqliteUpdates.sequence_number = updates.序号;
      }
      if (updates.备注 !== undefined) {
        sqliteUpdates.remarks = updates.备注;
      }
      
      const response = await fetch('/api/sqlite-devices', {
        method: 'PUT',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          deviceId,
          ...sqliteUpdates
        }),
      });

      if (!response.ok) {
        throw new Error('更新设备失败');
      }

      const data = await response.json();
      // 更新成功后刷新设备列表
      await fetchDevices();
      return data.device;
    } catch (err) {
      setError(err instanceof Error ? err.message : '未知错误');
      return null;
    }
  };

  const batchUpdateRemarks = async (updates: { deviceId: number; remarks: string }[]): Promise<boolean> => {
    try {
      setError(null);
      
      const response = await fetch('/api/sqlite-devices', {
        method: 'PATCH',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          action: 'batchUpdateRemarks',
          updates
        }),
      });

      if (!response.ok) {
        throw new Error('批量更新备注失败');
      }

      // 更新成功后刷新设备列表
      await fetchDevices();
      return true;
    } catch (err) {
      setError(err instanceof Error ? err.message : '未知错误');
      return false;
    }
  };

  const duplicateDevice = async (device: any): Promise<any | null> => {
    try {
      setError(null);
      
      // 创建新设备数据（不需要手动设置ID，由数据库自动生成）
      const newDevice: Partial<any> = {
        name: `${device.name}_副本`,
        classificationCode: device.classificationCode,
        classificationName: device.classificationName,
        specialty: device.specialty,
        namingTableId: device.namingTableId,
        positionTableId: device.positionTableId,
        baseParamsTableId: device.baseParamsTableId,
        techSpecTableId: device.techSpecTableId,
        序号: device.序号,
        备注: device.备注,
        '设备表及材料表中的实体对象名称': `${device['设备表及材料表中的实体对象名称']}_副本`,
        '对应的对象分类标准中的中文名称': device['对应的对象分类标准中的中文名称'],
        '分类码': device['分类码'],
        '对象命名': device['对象命名'],
        '位置信息': device['位置信息'],
        '基础参数': device['基础参数'],
        '技术规格书': device['技术规格书']
      };
      
      // 调用添加设备API
      return await addDevice(newDevice);
    } catch (err) {
      setError(err instanceof Error ? err.message : '未知错误');
      return null;
    }
  };

  const deleteDevice = async (deviceId: string): Promise<boolean> => {
    try {
      setError(null);
      
      console.log('useUnifiedDevices.deleteDevice调用:', deviceId);
      
      const response = await fetch(`/api/sqlite-devices?deviceId=${encodeURIComponent(deviceId)}`, {
        method: 'DELETE',
      });
      
      console.log('删除设备API响应状态:', response.status, response.statusText);
      
      if (!response.ok) {
        const errorText = await response.text();
        console.error('删除设备API错误响应:', errorText);
        throw new Error('删除设备失败');
      }
      
      const data = await response.json();
      console.log('删除设备API响应数据:', data);
      
      // 删除成功后刷新设备列表
      await fetchDevices();
      return data.success;
    } catch (err) {
      console.error('deleteDevice错误:', err);
      setError(err instanceof Error ? err.message : '未知错误');
      return false;
    }
  };

  return {
    devices,
    loading,
    error,
    refetch: fetchDevices,
    addDevice,
    updateDevice,
    batchUpdateRemarks,
    duplicateDevice,
    deleteDevice,
  };
} 